import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Tag } from './entities/tag.entity';
import { CreateTagDto } from './dto/create-tag.dto';
import { UpdateTagDto } from './dto/update-tag.dto';
import { User } from '../users/entities/user.entity';

@Injectable()
export class TagsService {
  constructor(
    @InjectRepository(Tag)
    private tagsRepository: Repository<Tag>,
  ) {}

  async create(createTagDto: CreateTagDto, user: User): Promise<Tag> {
    const tag = this.tagsRepository.create({
      ...createTagDto,
      user,
    });

    return this.tagsRepository.save(tag);
  }

  async findAll(user: User): Promise<Tag[]> {
    return this.tagsRepository.find({
      where: { user: { id: user.id } },
      order: { name: 'ASC' },
    });
  }

  async findOne(id: number, user: User): Promise<Tag> {
    const tag = await this.tagsRepository.findOne({
      where: { id, user: { id: user.id } },
    });

    if (!tag) {
      throw new NotFoundException(`ID为 ${id} 的标签不存在`);
    }

    return tag;
  }

  async update(
    id: number,
    updateTagDto: UpdateTagDto,
    user: User,
  ): Promise<Tag> {
    const tag = await this.findOne(id, user);

    Object.assign(tag, updateTagDto);

    return this.tagsRepository.save(tag);
  }

  async remove(id: number, user: User): Promise<void> {
    const tag = await this.findOne(id, user);
    await this.tagsRepository.remove(tag);
  }
}
